package com.jeff.rps;

import java.text.MessageFormat;

public class Round
{
  private final Player player1;
  private final Player player2;

  private final Throw throw1;
  private final Throw throw2;

  public Round(Player p1, Throw t1, Player p2, Throw t2)
  {
    this.player1 = p1;
    this.throw1 = t1;
    this.player2 = p2;
    this.throw2 = t2;
  }

  public Player getWinner()
  {
    if (throw1.beats(throw2))
      return player1;
    else if (throw2.beats(throw1)) return player2;

    return null;
  }

  public Throw getMyThrow(Player me)
  {
    return me.equals(player1) ? throw1 : throw2;
  }

  public Throw getTheirThrow(Player me)
  {
    return me.equals(player1) ? throw2 : throw1;
  }

  @Override
  public String toString()
  {
    MessageFormat message = new MessageFormat(
        "{0} threw {1}\n{2} threw {3}\n{4}");

    Object[] params = new Object[5];
    params[0] = player1.getName();
    params[1] = throw1.name();
    params[2] = player2.getName();
    params[3] = throw2.name();

    if (player1.equals(getWinner()))
      params[4] = player1.getName() + " wins!";
    else if (player2.equals(getWinner()))
      params[4] = player2.getName() + " wins!";
    else
      params[4] = "Tie!";

    return message.format(params);
  }
}
